# -*- coding: utf-8 -*-

import time,PIL,os
from PIL import ImageGrab
import numpy as np
import time
from tempfile import NamedTemporaryFile
#import cv2
#from pprint import pprint
from concurrent.futures import ThreadPoolExecutor
import sys
import io
import re  # 新增导入

#sys.stdout.reconfigure(encoding='utf-8')
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

#截图
class ScreenCut:
    def __init__(self):
        if not os.path.exists("E:/ningyuan/sumimoto/Curelasto/tmp/"):
            os.makedirs("E:/ningyuan/sumimoto/Curelasto/tmp/")
        try:
            os.remove("E:/ningyuan/sumimoto/Curelasto/tmp/scr.png")
            os.remove("E:/ningyuan/sumimoto/Curelasto/tmp/cut.png")
        except:pass
        self.scrImg = open("E:/ningyuan/sumimoto/Curelasto/tmp/scr.png","wb+")
        self.cutImg = open("E:/ningyuan/sumimoto/Curelasto/tmp/cut.png","wb+")
    def cut(self):
        self.scrren_cut()
        #print("截图完成")
    def scrren_cut(self):
        # 获取传递给Python脚本的参数
        arg1 = sys.argv[1]
        arg2 = sys.argv[2]
        x = int(arg1)  # 将第一个参数转换为整数
        y = int(arg2)  # 将第二个参数转换为整数
        #print("x is:", x)
        #print("y is:", y)
         # 截取固定区域 (500,500) 到 (600,600)
#         img = ImageGrab.grab(bbox=(
#                 1000,       # 起始x坐标
#                 600,       # 起始y坐标
#                 1000+800,  # 起始x + 宽度
#                 600+500   # 起始y + 高度
#             ))
        img = ImageGrab.grab(bbox=(
            x,       # 起始x坐标
            y,       # 起始y坐标
            x+350,  # 起始x + 宽度
            y+60   # 起始y + 高度
        ))
        img.save(self.cutImg.name)

class OCR:
    def __init__(self,imagePath,instPack=None,**kwargs):
        from paddleocr import PaddleOCR
        # 路径可替换为你的项目文件夹或随便一个专门装PaddleOCR模型的文件夹路径
        self.paddleocr = PaddleOCR(
                                    lang='ch', # 指定中文语言
                                    use_angle_cls=False, # 中文通常不需要角度分类
                                    det_db_unclip_ratio=2.0,  # 增加文本框扩展比例
                                    #rec_char_dict_path="E:/ningyuan/sumimoto/Curelasto/code/curelasto-services/doc/keys.txt",
                                    **kwargs  # 统一通过关键字参数传递额外参数
                                    )
        self.imagePath = imagePath
        self.instPack = instPack  # 明确接收参数
    def ocr(self,**kwargs):
        result = self.paddleocr.ocr(self.imagePath,**kwargs)[0]
        if not result:
            return None
        rd = list(map(lambda i:{"block":{
                                         "topleft":(i[0][0][0],i[0][0][1]),
                                         "topright":(i[0][1][0], i[0][1][1]),
                                         "bottomleft":(i[0][2][0], i[0][2][1]),
                                         "bottomright":(i[0][3][0], i[0][3][1])
                                         },
                                "text":i[1][0],
                                "confidence":i[1][1]},
                      result))

        return rd

cut = ScreenCut()
#print("Init done.")

cut.cut()
#print("cut done.")

#ocr = OCR("E:/ningyuan/sumimoto/Curelasto/tmp/cut.png")
ocr = OCR(
    imagePath="E:/ningyuan/sumimoto/Curelasto/tmp/cut.png",
    instPack='123456789'  # 确保只在此处传递一次
)

if not os.path.exists("E:/ningyuan/sumimoto/Curelasto/tmp/cut.png"):
    #print("已取消截图")
    exit()
result = ocr.ocr()


# 用于存储提取的文本
extracted_text = ''
print("result:",result)
for line in result:
    print("line:",line)
    # 去除文本中的特殊字符
    #filtered_text = re.sub(r'[^\w\s()\[\]{}<>]', '', line['text'])
    filtered_text = re.sub(r'[^\w\s.()\[\]{}<>]', '', line['text'])  # 添加小数点到白名单
    extracted_text += filtered_text
    #extracted_text += line['text']

if not result:
    #print("未识别到文字")
    print("Text not recognized")
    exit()
# 可选：移除所有括号（如需保留请删除此段）
extracted_text = extracted_text.replace('(', '').replace(')', '')
#print("ocr-result:",extracted_text)
print(extracted_text)
